package com.hxd.otc.module.my.model;

import com.hxd.otc.api.IUploadApi;
import com.hxd.otc.common.HostType;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.net.RetrofitManager;
import com.uber.autodispose.AutoDisposeConverter;

import java.io.File;
import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by lzy on 2018/6/14 0014.
 * description ${上传图片Model}
 */
public class UploadImageModel {

    private static class SingletonHolder {
        private static final UploadImageModel instance = new UploadImageModel();
    }

    public static UploadImageModel getInstance() {
        return UploadImageModel.SingletonHolder.instance;
    }


    public void uploadImage(File file, Observer observer, AutoDisposeConverter<String> converter) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RequestBody tokenBody = RequestBody.create(MediaType.parse("multipart/form-data"), UserHelper.getToken());

        HashMap<String, RequestBody> bodyHashMap = new HashMap<>();
        bodyHashMap.put("token", tokenBody);

        getUploadApi().uploadImage(bodyHashMap, filePart)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .as(converter)
                .subscribe(observer);
    }

    public void uploadCardImage(File file, Observer observer, AutoDisposeConverter<String> converter) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RequestBody tokenBody = RequestBody.create(MediaType.parse("multipart/form-data"), UserHelper.getToken());

        HashMap<String, RequestBody> bodyHashMap = new HashMap<>();
        bodyHashMap.put("token", tokenBody);

        getUploadApi().uploadCardImage(bodyHashMap, filePart)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .as(converter)
                .subscribe(observer);
    }

    private IUploadApi getUploadApi() {
        return RetrofitManager.getInstance(HostType.HOST_UPLOAD_IMAGE).create(IUploadApi.class);
    }
}
